/**
 * @file condition_variable_wait_for.cpp
 * @brief: 演示condition_variable::wait_for的用法
 * @note: 不要在window上运行！垃圾windows!!!!
 */


#include<iostream>
#include<thread>
#include<chrono>
#include<mutex>
#include<condition_variable>

std::mutex m;
std::condition_variable cv;

void f1(void)
{
	auto t = std::chrono::steady_clock::now();
	
	while (1)
	{
		std::unique_lock<std::mutex> lock(m);
		auto res = cv.wait_for(lock, std::chrono::seconds(3));
		auto n = std::chrono::steady_clock::now();
		auto duration = n - t;
		auto timecount = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
		std::cout << timecount << ": " << ((std::cv_status::timeout == res) ? "timeout...." : "signal get!") << std::endl;

		if (std::cv_status::timeout != res)
		{
			break;
		}
	}
}

void f2(void)
{
	std::this_thread::sleep_for(std::chrono::seconds(20));
	std::unique_lock<std::mutex> lock(m);
	std::cout << "cv notify" << std::endl;
	cv.notify_one();
}

int main(void)
{
	std::thread t1(f1);
	std::thread t2(f2);

	t2.join();
	t1.join();

	return 0;
}
